import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { apiService } from '@/services/api'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const isLoggedIn = computed(() => !!user.value)
  const userRole = computed(() => user.value?.role || null)

  const login = (userData) => {
    user.value = userData
    localStorage.setItem('user', JSON.stringify(userData))
  }

  const logout = () => {
    user.value = null
    localStorage.removeItem('user')
  }

  const initializeAuth = () => {
    const storedUser = localStorage.getItem('user')
    if (storedUser) {
      user.value = JSON.parse(storedUser)
    }
  }

  const validateUser = async (username, password) => {
    try {
      const user = await apiService.getUserByUsername(username)
      if (user && user.password === password) {
        return user
      }
    } catch (error) {
      console.error('登录验证失败:', error)
    }
    return null
  }

  // 注册用户
  const registerUser = async (userData) => {
    try {
      // 检查用户名是否已存在
      const existingUser = await apiService.getUserByUsername(userData.username)
      if (existingUser) {
        throw new Error('用户名已存在')
      }
      
      // 创建新用户
      const newUser = await apiService.createUser({
        ...userData,
        id: Date.now(),
        enrolledCourses: []
      })
      
      return newUser
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    }
  }

  return {
    user,
    isLoggedIn,
    userRole,
    login,
    logout,
    initializeAuth,
    validateUser,
    registerUser
  }
})